/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.security.user.UserDetail;
import com.chengcang.admin.modules.sys.dao.SysRoleDao;
import com.chengcang.admin.modules.sys.dao.SysRoleUserDao;
import com.chengcang.admin.modules.sys.dto.SysRoleDTO;
import com.chengcang.admin.modules.sys.entity.SysRoleEntity;
import com.chengcang.admin.modules.sys.service.*;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.enums.SuperAdminEnum;
import com.chengcang.common.page.PageData;
import com.chengcang.common.service.impl.BaseServiceImpl;
import com.chengcang.common.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色
 *
 * @author zhanli
 */
@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleDataScopeService sysRoleDataScopeService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Autowired
    private SysRoleUserDao sysRoleUserDao;
    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public PageData<SysRoleDTO> page(Map<String, Object> params) {
        IPage<SysRoleEntity> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );

        PageData<SysRoleDTO> pageData = getPageData(page, SysRoleDTO.class);
        List<Long> roleIds = pageData.getList().stream().map(SysRoleDTO::getId).collect(Collectors.toList());
        Map<Long, Long> roleCountMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            List<Map<Long, Long>> selectCountList = sysRoleUserDao.countByRoleId(roleIds);
            if (selectCountList.size() > 0) {
                roleCountMap = selectCountList.stream().collect(Collectors.toMap(o -> o.get("role_id"), o -> o.getOrDefault("count", 0L)));
            }
        }

        for (SysRoleDTO dto : pageData.getList()) {
            Long count = roleCountMap.get(dto.getId());
            dto.setMemberCount(count == null ? 0L : count);
        }

        return pageData;
    }

    @Override
    public List<SysRoleDTO> list(Map<String, Object> params) {
        QueryWrapper<SysRoleEntity> wrapper = getWrapper(params);
        wrapper.eq("status", 0);
        wrapper.eq(SecurityUser.getTenantId() != null, "tenant_id", SecurityUser.getTenantId());
        List<SysRoleEntity> entityList = baseDao.selectList(wrapper);

        return ConvertUtils.sourceToTarget(entityList, SysRoleDTO.class);
    }

    private QueryWrapper<SysRoleEntity> getWrapper(Map<String, Object> params) {
        String name = (String) params.get("name");

        QueryWrapper<SysRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name), "name", name);

        //普通管理员，只能查询所属部门及子部门的数据
        UserDetail user = SecurityUser.getUser();
        if (SecurityUser.getUserType() == SuperAdminEnum.NO.value() && null != user.getDeptId()) {
            List<Long> deptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
            wrapper.in(CollectionUtils.isNotEmpty(deptIdList), "dept_id", deptIdList);
        }

        return wrapper;
    }

    @Override
    public SysRoleDTO get(Long id) {
        SysRoleEntity entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, SysRoleDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysRoleDTO dto) {
        SysRoleEntity entity = ConvertUtils.sourceToTarget(dto, SysRoleEntity.class);
        entity.setTenantId(SecurityUser.getTenantId());
        entity.setStatus(0);
        //保存角色
        insert(entity);

        //保存角色菜单关系
        sysRoleMenuService.saveOrUpdate(entity.getId(), dto.getMenuIdList());

        //保存角色数据权限关系
        sysRoleDataScopeService.saveOrUpdate(entity.getId(), dto.getDeptIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRoleDTO dto) {
        SysRoleEntity entity = ConvertUtils.sourceToTarget(dto, SysRoleEntity.class);

        //更新角色
        updateById(entity);

        //更新角色菜单关系
        sysRoleMenuService.saveOrUpdate(entity.getId(), dto.getMenuIdList());

        //更新角色数据权限关系
        sysRoleDataScopeService.saveOrUpdate(entity.getId(), dto.getDeptIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        //删除角色
        baseDao.deleteBatchIds(Arrays.asList(ids));

        //删除角色用户关系
        sysRoleUserService.deleteByRoleIds(ids);

        //删除角色菜单关系
        sysRoleMenuService.deleteByRoleIds(ids);

        //删除角色数据权限关系
        sysRoleDataScopeService.deleteByRoleIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copy(SysRoleDTO dto) {
        SysRoleDTO sourceRole = get(dto.getId());
        // 获取角色菜单关系
        List<Long> menuIdList = sysRoleMenuService.getMenuIdList(dto.getId());
        // 获取角色数据权限关系
        List<Long> deptIdList = sysRoleDataScopeService.getDeptIdList(dto.getId());
        sourceRole.setId(null);
        sourceRole.setName(dto.getName());
        sourceRole.setRemark(dto.getRemark());
        sourceRole.setMenuIdList(menuIdList);
        sourceRole.setDeptIdList(deptIdList);
        save(sourceRole);
    }

}